<?php

require_once __DIR__."/../constants.php";
require_once VENDOR_DIR."autoload.php";

use Predis\Client;
$redis = new Client('tcp://127.0.0.1:6379');

const HASH_CONTENT_LIST = "hash:content:list";
const HASH_DESCRIPTION = "hash:description";
const HASH_CATEGORY_LIST = "hash:category:list";

$cmdArray = $redis->hkeys(HASH_CONTENT_LIST);
$categoryList = $redis->hkeys(HASH_CATEGORY_LIST);
$cmd = $cmdArray[mt_rand(0, count($cmdArray) -1)];

if(!isset($_GET['category']) && !isset($_GET['cmd'])) {
    category($redis,$categoryList[0]);exit;
} else  {
    if(isset($_GET['category']) && in_array($_GET['category'], $categoryList)) {
        $category = $_GET['category'];
        category($redis,$category);exit;
    }
    if(isset($_GET['cmd']) && in_array($_GET['cmd'], $cmdArray)) {
        $cmd = $_GET['cmd'];
        cmd($redis,$cmd);exit;
    }
    //其它情况
    //header("Resource Not Found", true,404);
    $data = [
        'categoryList'=> $categoryList,
        'msg'=>'命令未找到',
    ];
    render('cmd.twig', $data);exit;
}
function  cmd(Predis\Client $redis, $cmd)
{
    global $categoryList;

    $cmdInfo = $redis->hget(HASH_CONTENT_LIST, $cmd);
    $cmdInfoArray = json_decode($cmdInfo,true);
    $cmdInfoArray['categoryList'] = $categoryList;
    sort($cmdInfoArray['categoryList']);
    render('cmd.twig',$cmdInfoArray);
}

function category(Predis\Client $redis,$category)
{
    global $categoryList;

    $categoryCmdInfo = $redis->hget(HASH_CATEGORY_LIST,$category);
    $categoryCmdList = json_decode($categoryCmdInfo, true);
    sort($categoryCmdList);
    $categoryCmdRawInfoList = $redis->hmget(HASH_CONTENT_LIST,$categoryCmdList);
    $store = [];
    foreach ($categoryCmdRawInfoList as $cmd =>$categoryCmdRawInfo) {
        $store[$cmd] = json_decode($categoryCmdRawInfo, true);
    }
    $data = [
        'cmdInfoList'=>$store,
        'category'=>$category,
        'categoryList'=>$categoryList,
    ];
    render('category.twig',$data);
}

function render($fileName,$data)
{
    $loader = new Twig_Loader_Filesystem(rtrim(TPL_DIR, "/"));
    $twig = new Twig_Environment($loader, [
        'cache' =>rtrim(TPL_CACHE_DIR,"/"),
        'autoescape'=>false,
    ]);
    echo $twig->render($fileName,$data);
}



